﻿using System;
using System.Configuration;
using System.Web.Configuration;

namespace VioletDevelopmentLaboratory.Net.Web.Configuration
{
	public sealed class AuthorizationSectionManager : ConfigurationManagerBase
	{
		private AuthorizationSection section;

		public AuthorizationSectionManager()
		{
			this.section = (AuthorizationSection)base.GetConfigurationSection("system.web/authorization");
		}

		public void Add(int index, AuthorizationRuleAction action, string roles, string users, string verbs)
		{
			AuthorizationRule newRule = new AuthorizationRule(action);
			if (!string.IsNullOrEmpty(roles))
			{
				newRule.Roles.AddRange(roles.Split(new char[] { ',' }));
			}
			if (!string.IsNullOrEmpty(users))
			{
				newRule.Users.AddRange(users.Split(new char[] { ',' }));
			}
			if (!string.IsNullOrEmpty(verbs))
			{
				newRule.Verbs.AddRange(verbs.Split(new char[] { ',' }));
			}

			this.section.Rules.Set(index, newRule);
			this.Save();
		}

		public void Modify(int index, AuthorizationRuleAction action, string roles, string users, string verbs)
		{
			this.section.Rules[index].Action = action;

			if (!string.IsNullOrEmpty(roles))
			{
				this.section.Rules[index].Roles.Clear();
				this.section.Rules[index].Roles.AddRange(roles.Split(new char[] { ',' }));
			}
			if (!string.IsNullOrEmpty(users))
			{
				this.section.Rules[index].Users.Clear();
				this.section.Rules[index].Users.AddRange(users.Split(new char[] { ',' }));
			}
			if (!string.IsNullOrEmpty(verbs))
			{
				this.section.Rules[index].Verbs.Clear();
				this.section.Rules[index].Verbs.AddRange(verbs.Split(new char[] { ',' }));
			}

			this.Save();
		}

		public void Remove(int index)
		{
			this.section.Rules.RemoveAt(index);
			this.Save();
		}

		public AuthorizationRule GetRule(int index)
		{
			return this.section.Rules[index];
		}

		public AuthorizationRuleCollection GetRuleCollection()
		{
			return this.section.Rules;
		}
	}
}
